<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <title>广告管理</title>
    <base href="<%=basePath %>"/>
    <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.css"/>
    <link rel="stylesheet" href="assets/bootstrap-fileinput/css/fileinput.css">
    <link rel="stylesheet" href="assets/bootstrap-fileinput/themes/explorer/theme.css">
    <%--<link rel="stylesheet" href="assets/layui/css/layui.css">--%>
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/jquery.validator.min.js"></script>
    <script src="assets/bootstrap/js/bootstrap.min.js"></script>
    <script src="assets/bootstrap-fileinput/js/fileinput.js"></script>
    <script src="assets/bootstrap-fileinput/js/locales/zh.js"></script>
    <script src="assets/bootstrap-fileinput/themes/explorer/theme.js"></script>
    <script src="assets/layui/layui.all.js"></script>
    <style>
        .td{width:150px;overflow:hidden}
    </style>
</head>
<body>
<div class="container">
    <div class="col-lg-10 col-lg-offset-1">
        <div class="panel-body">
            <form id="selectForm" class="form-horizontal">
                <div class="panel-body">
                    广告名：<input calss="form-group-sm input" type="text" name="advertName">
                    <a class="btn-primary btn-sm" onclick="getAdverts(1)">搜索</a>
                </div>
            </form>
        </div>
        <div>
            <table class="table table-hover table-bordered <%--table table-border table-bordered table-hover table-bg table-sort--%>">
                <thead>
                <tr class="text-c">
                    <th width="80" style="text-align: center">广告名</th>
                    <th width="100" style="text-align: center">图片</th>
                    <th width="100" style="text-align: center">开始时间</th>
                    <th width="100" style="text-align: center">结束时间</th>
                    <th width="100" style="text-align: center">操作</th>
                </tr>
                </thead>
                <tbody style="text-align: center" id="advertTbody">
                <tr class="text-c">
                    <td colspan="5">
                        加载中。。。
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <div style="float: left">
            <a class="btn-primary btn-sm" data-toggle='modal' data-target='#addModal'>新增广告</a>
        </div>
        <div id="page" style="float: right">
            总共1页，当前第1页，一页5行，总共0行。
            <a class="btn-sm btn-primary" onclick="getAdverts(1)">上一页</a>
            <a class="btn-sm btn-primary" onclick="getAdverts(1)">下一页</a>
        </div>
    </div>
</div>
<div class="modal fade" id="addModal">
    <div class="modal-dialog" style="width: 800px">
        <div class="modal-content">
            <!-- 模态框头部 -->
            <div class="modal-header" style="text-align: center">
                <label>新增广告</label>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body" style="overflow:auto">
                <form id="addForm" class=" form-horizontal col-lg-offset-2">
                    <table>
                        <tr>
                            <td>广告名：</td>
                            <td><input class="form-control" type="text" name="advertName" id="advertName" onblur="nonEmpty(this.id,'广告名')"></td>
                        </tr>
                        <tr>
                            <td>起始时间：</td>
                            <td><input type="text" class="form-control" id="date1" name="beginTime"></td>
                        </tr>
                        <tr>
                            <td>结束时间：</td>
                            <td><input type="text" class="form-control" id="date2" name="finishTime"></td>
                        </tr>
                        <tr>
                            <td>图片：</td>
                            <td>
                                <input type="file" name="add_file" id="add_file" class="file-loading" />
                            </td>
                        </tr>
                    </table>
                </form>
            </div>
            <div class="modal-footer">
                <a class="btn-primary btn-sm" onclick="add()">添加</a>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="detailsModal">
    <div class="modal-dialog" style="width: 600px">
        <div class="modal-content">
            <!-- 模态框头部 -->
            <div class="modal-header" style="text-align: center">
                <label>广告详情</label>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body" style="overflow:auto">
                <form id="detailsForm" class=" form-horizontal col-lg-offset-2">
                    加载中。。。
                </form>
            </div>
            <div class="modal-footer">
                <a class="btn-primary btn-sm" onclick="updateAdvert()">保存修改</a>
            </div>
        </div>
    </div>
</div>

</body>
</html>
<script>

    $(document).ready(function () {
        layui.use('laydate', function () {
            var laydate = layui.laydate;
            //执行一个laydate实例
            laydate.render({
                elem: '#date1'//指定元素
            });
            //执行一个laydate实例
            laydate.render({
                elem: '#date2'//指定元素
            });
        });
        //搜索广告列表
        getAdverts(1);
        //0.初始化fileinput
        var oFileInput = new FileInput();
        oFileInput.Init("add_file", "advert/upload.action");
    });

    function getAdverts(pageNum) {
        if (pageNum!=0) {
            $.post(
                "advert/getAdverts.action?pageNum="+pageNum,
                $('#selectForm').serialize(),
                function (data) {
                    if (data.list.length == 0) {
                        $('#advertTbody').html(null);
                        $('#advertTbody').append(
                            "<tr>" +
                            "<td colspan='5'>没有符合条件的数据</td>" +
                            "</tr>"
                        );
                    } else {
                        $('#advertTbody').html(null);
                        var str;
                        data.list.forEach(function (v) {
                            str += "<tr><td>" + v.advertName + "</td>" +
                                "<td><img src='"+v.url+"' style='max-height:145px; max-width: 120px; vertical-align:middle'></td>" +
                                "<td>" + v.beginTime + "</td>" +
                                "<td>" + v.finishTime + "</td>" +
                                // "<td><a class='btn-primary btn-sm'data-toggle='modal' data-target='#detailsModal' onclick='details("+v.advertId+")'>修改</a> " +
                                    "<td><a class='btn-primary btn-sm'onclick='del("+v.advertId+")'>删除</a>"+
                                "</td></tr>"
                        });
                        $('#advertTbody').append(str);
                    }
                    $('#page').html(null);
                    $('#page').append("总共" + data.pages + "页，当前第" + data.pageNum + "页，一页" + data.pageSize + "行，总共" + data.total + "行。");
                    $('#page').append("<a class='btn-sm btn-primary' onclick='getAdverts(" + data.prePage + ")'>上一页</a> ");
                    $('#page').append("<a class='btn-sm btn-primary' onclick='getAdverts(" + data.nextPage + ")'>下一页</a>");

                }
            )
        }
    }

    function add() {
        if (nonEmpty('advertName',"广告名")) {
            if (nonEmpty('date1',"起始时间")) {
                if (nonEmpty('date2',"结束时间")) {
                    $('#add_file').fileinput('upload');
                }
            }
        }
    }

    //修改建议
    function updateAdvert() {
        if (nonEmpty('advertName',"广告名")) {
            if (nonEmpty('date1',"起始时间")) {
                if (nonEmpty('date2',"结束时间")) {
                    $.post(
                        "advert/updateAdvert.action",
                        $('#detailsForm').serialize(),
                        function (str) {
                            if (str=="true") {
                                alert("修改成功！");
                            }else {
                                alert("修改失败！");
                            }
                        }
                    )
                }
            }
        }
    }

    //详情
    function details(advertId) {
        $.post(
            "advert/getAdvert.action",
            {'advertId':advertId},
            function (data) {
                var str = "<table><tr>"+
                        "<td>广告名：</td>"+
                        "<td><input class='form-control' value='"+data.advertName+"' type='text' name='advertName' onblur='nonEmpty(this.id,'广告名')'></td>" +
                        "</tr><tr>"+
                        "<td>起始时间：</td>"+
                        "<td><input type='text' value='"+data.beginTime+"' class='form-control' id='date1' name='beginTime'></td>" +
                        "</tr><tr>"+
                        "<td>结束时间：</td>"+
                        "<td><input type='text' value='"+data.finishTime+"' class='form-control' id='date2' name='finishTime'></td>"+
                        "</tr><tr>"+
                        " <td>图片：</td>"+
                        " <td><img src='"+data.url+"' style='max-height:145px; max-width: 120px; vertical-align:middle'></td>"+
                        "<td><input type='file' name='up_file' id='up_file' class='file-loading'></td>"+
                        "</tr></table>"+
                        "<input hidden name='advertId' value='"+data.advertId+"'>"
                $('#detailsForm').html(null);
                $('#detailsForm').append(str);
            }
        )
    }

    //前端非空验证（标签ID，提示语）
    function nonEmpty(input, tips) {
        var inputval = $("#" + input).val();
        if (!inputval) {
            layer.tips('请输入'+tips+'!', '#' + input, {tips: [2, '#CC3333']});
            return false;
        }
        return true;
    }

    function del(advertId) {
        $.post(
            "advert/delAdvert.action",
            {'advertId':advertId},
            function (data) {
                if (data=="true") {
                    alert("删除成功！");
                    getAdverts(1);
                }else {
                    alert("删除失败！");
                    getAdverts(1);
                }
            }
        )
    }

    //关闭模态框后
    $('#detailsModal').on('hidden.bs.modal', function () {
        getAdverts(1);
    })
    $('#addModal').on('hidden.bs.modal', function () {
        getAdverts(1);
        $('#abbreviation').val(null);
        $('#content').val(null);
    })

    //初始化fileinput
    var FileInput = function () {
        var oFile = new Object();

        //初始化fileinput控件（第一次初始化）
        oFile.Init = function(ctrlName, uploadUrl) {
            var control = $('#' + ctrlName);

            //初始化上传控件的样式
            control.fileinput({
                language: 'zh', //设置语言
                uploadUrl: uploadUrl, //上传的地址
                allowedFileExtensions: ['jpg', 'gif', 'png', 'bmp', 'jpeg'],//接收的文件后缀
                showUpload: false, //是否显示上传按钮
                showCaption: false,//是否显示标题
                browseClass: "btn btn-primary", //按钮样式
                //dropZoneEnabled: false,//是否显示拖拽区域
                //minImageWidth: 50, //图片的最小宽度
                //minImageHeight: 50,//图片的最小高度
                //maxImageWidth: 1000,//图片的最大宽度
                //maxImageHeight: 1000,//图片的最大高度
                //maxFileSize: 0,//单位为kb，如果为0表示不限制文件大小
                //minFileCount: 0,
                maxFileCount: 1, //表示允许同时上传的最大文件个数
                enctype: 'multipart/form-data',
                validateInitialCount:true,
                previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
               // msgFilesTooMany: "最多只能上传({n}) 超过允许的最大数值{m}！",
                msgFilesTooMany: "一次只能上传{m}张图片！",
                layoutTemplates :{
                    // actionDelete:'', //去除上传预览的缩略图中的删除图标
                    actionUpload:'',//去除上传预览缩略图中的上传图片；
                    //actionZoom:''   //去除上传预览缩略图中的查看详情预览的缩略图标。
                },
            });

                //添加广告中导入文件上传完成之后的事件
                $("#add_file").on("fileuploaded", function (event, data, previewId, index) {
                    var result = data.response; //后台返回的json
                    console.log(result);
                    $.post(
                        "advert/addAdvert.action?url="+result.url,
                        $('#addForm').serialize(),
                        function (str) {
                            if (str == "true") {
                                alert("添加成功！");
                            } else {
                                alert("添加失败！");
                            }
                        }
                    )
                });
                //修改广告中导入文件上传完成之后的事件
                $("#up_file").on("fileuploaded", function (event, data, previewId, index) {
                    var result = data.response; //后台返回的json
                    console.log(result);
                    $.post(
                        "advert/updateAdvert.action?url="+result.url,
                        $('#detailsForm').serialize(),
                        function (str) {
                            if (str == "true") {
                                alert("修改成功！");
                            } else {
                                alert("修改失败！");
                            }
                        }
                    )
                }
            );

        }
        return oFile;
    };


</script>